package com.lyj.mp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lyj.mp.domain.dto.PageDTO;
import com.lyj.mp.domain.enums.UserStatus;
import com.lyj.mp.domain.po.Address;
import com.lyj.mp.domain.po.User;
import com.lyj.mp.domain.query.UserQuery;
import com.lyj.mp.domain.vo.AddressVO;
import com.lyj.mp.domain.vo.UserVO;
import com.lyj.mp.mapper.UserMapper;
import com.lyj.mp.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    //根据id扣减余额
    @Transactional //加事务和乐观锁二选一
    @Override
    public String deductionBalance(long id, Integer money) {
        // 1、查询用户
        User user = getById(id); // 在service中调自己的方法
        // 2、校验用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            return "用户状态异常";
        }
        // 3、校验余额是否充足
        if (user.getBalance() < money) {
            return "用户余额不足";
        }
        // 4、扣减余额
//        userMapper.deductionBalance(id, money);
        int newBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, newBalance)
                .set(newBalance == 0,User::getStatus,UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance,user.getBalance()) //乐观锁
                .update();
        return null;
    }

    //根据复杂条件查询
    @Override
    public List<UserVO> selectConditions(String name, UserStatus status, Integer maxBalance, Integer minBalance) {

        List<User> userList = lambdaQuery()
                .like(name != null, User::getUsername, name) //模糊
                .eq(status != UserStatus.FROZEN, User::getStatus, status) //判断
                .ge(minBalance != null, User::getBalance, minBalance) //大于
                .le(maxBalance != null, User::getBalance, maxBalance) //小于
//                .one() 查一个
                .list();//查询多个
//                .count() 统计
//                .page() 分页查询
//                .exist() 判断数据存不存在
        return BeanUtil.copyToList(userList, UserVO.class);
    }

    // 根据id查用户和地址信息
    @Override
    public UserVO selectUserAndAddressById(Long id) {
        // 1、根据id查用户信息  封装为vo
        User user = getById(id);
        // 1.1、校验数据
        if (user == null || user.getStatus() == UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常！");
        }
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        // 2、查询地址 封装vo
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id).list();
        // 2.1、如果查不到地址 就直接返回用户信息
        if (CollUtil.isEmpty(addresses)){
            return userVO;
        }
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        // 3、 将地址存入用户信息中
        userVO.setAddresses(addressVOS);
        return userVO;
    }

    // 根据id批量查询用户信息和地址
    @Override
    public List<UserVO> selectUserAndAddressByIds(List<Long> ids) {
        // 1、先查用户集合
        List<User> users = listByIds(ids);
        if (users == null || CollUtil.isEmpty(users)){
            return Collections.emptyList(); //返回空List
        }
        // 2、查地址
        // 2.1、先获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        // 2.2、根据id查地址
        List<Address> addressList = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        // 2.3、转换地址Vo
        List<AddressVO> addressVOList = BeanUtil.copyToList(addressList, AddressVO.class);
        // 2.4、用户地址集合分组处理 相同的放在一起
        Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)){
            addressMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }

        // 3、转换VO返回
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(addressMap.get(user.getId()));
            list.add(userVO);
        }
        return list;
    }

    @Override
    public PageDTO<UserVO> selectPage(UserQuery userQuery) {
        String name = userQuery.getName();
        UserStatus status = userQuery.getStatus();
        Integer minBalance = userQuery.getMinBalance();
        Integer maxBalance = userQuery.getMaxBalance();
        // 1、构建分页条件
        Page<User> page = userQuery.toMpPage(new OrderItem(userQuery.getSortBy(), userQuery.getIsAsc()));
        // 2、分页查询
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance) //大于
                .le(maxBalance != null, User::getBalance, maxBalance) //小于
                .page(page);
        // 4、返回
        return PageDTO.of(p,UserVO.class);
    }
}

























